package com.bort.system.config;

import com.bort.system.filter.AccessFilter;
import com.bort.system.security.AdminShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
class ShiroConfig {


    @Bean("hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式为MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(1);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    // 创建Realm
    @Bean("adminShiroRealm")
    public AdminShiroRealm myRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher) {
        AdminShiroRealm realm = new AdminShiroRealm();
        realm.setCredentialsMatcher(matcher);
        return  realm;
    }

    // 创建SecurityManager
    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("adminShiroRealm") AdminShiroRealm adminShiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(adminShiroRealm);
        return securityManager;
    }

    // 配置Shiro的过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 配置过滤规则
        Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
        filters.put("authc",new AccessFilter());
        Map<String, String> map = new HashMap<String, String>();
        map.put("/image", "anon");
        map.put("/admin/**", "authc");
        shiroFilterFactoryBean.setLoginUrl("/admin/login");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

}
